﻿using ByteSite.API.Model;
using ByteSite.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using Yitter.IdGenerator;

namespace ByteSite.API.Controllers
{
    [RoutePrefix("api/order")]
    public class OrderController : ApiController
    {
        protected internal Entitys.sysconfig sysConfig;
        public OrderController()
        {
            sysConfig = new BLL.sysconfig().loadConfig();
        }

        [HttpPost]
        [Route("submit")]
        public HttpResponseMessage submit()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            //StringBuilder builder = new StringBuilder();
            //foreach (string item in request.Form.Keys)
            //{
            //    builder.AppendFormat("{0}:{1}", item, request.Form[item]);
            //    builder.AppendLine();
            //}

            //FileStream fs = new FileStream(@"C:\wwwroot\qlyc\api\log.txt", FileMode.Create);
            ////获得字节数组
            //byte[] data = System.Text.Encoding.Default.GetBytes(builder.ToString());
            ////开始写入
            //fs.Write(data, 0, data.Length);
            ////清空缓冲区、关闭流
            //fs.Flush();
            //fs.Close();

            SubmitRequest req = DTRequest.RequestFormParams<SubmitRequest>(request);

            //req = JsonHelper2.JSONToObject<SubmitRequest>("{\"invoice_mobile\":\"123123123\",\"city\":\"110100\",\"invoice_title\":\"发票抬头\",\"freight\":\"0\",\"county\":\"110102\",\"remark\":\"\",\"invoice_name\":\"东营开发区讯通网络工作室\",\"mode\":\"1\",\"invoice_org_code\":\"111231231232132131\",\"province\":\"110000\",\"invoice_type\":\"1\",\"payment\":\"5\",\"sku\":\"[{\\\"mode\\\":1,\\\"price\\\":6199.00,\\\"num\\\":1,\\\"sku\\\":\\\"108\\\"}]\",\"email\":\"\",\"zip\":\"100000\",\"address\":\"订单测试地址\",\"invoice_receipt_address\":\"收票地址\",\"mobile\":\"18788881111\",\"order_price\":\"6199.00\",\"dep_name\":\"订单测试采购单位\",\"token\":\"qlycapi98bf71c8fc884b9264bbc7ed2\",\"phone\":\"18788881111\",\"yggc_order\":\"dykfqxt210505233107d9b1c866-47b9-4e06-8c4f-7354334a5bcc\",\"name\":\"东营开发区讯通网络工作室的测试订单\",\"platformCode\":\"ZF00004\"}");
            req.skuObj = JsonHelper2.JSONToObject<List<SubmitSku>>(req.sku);
            BaseResponse resp = new BaseResponse();

            Entitys.dt_orders model = new Entitys.dt_orders();
            model.site_id = 1; //当前站点ID
            model.order_no = "B" + YitIdHelper.NextId().ToString(); //订单号B开头为商品订单
            model.user_id = 1;
            model.user_name = "qlyc";
            model.payment_id = Utils.ObjToInt(req.payment);//1：货到付款，2：集中支付， 3：在线支付， 4：支票 5：账期支付 6：先款后货
            model.express_id = 1;
            model.accept_name = req.name;
            model.area = req.province + "," + req.city + "," + req.county; //省市区以逗号相隔
            model.address = req.address;
            model.telphone = req.phone;
            model.mobile = req.mobile;
            model.message = req.remark;
            model.email = req.email;
            model.post_code = req.zip;
            model.accept_com_name = req.dep_name;
            
            model.is_invoice = 1;
            model.invoice_title = req.invoice_title;
            model.invoice_type = req.invoice_type;
            model.invoice_org_code = req.invoice_org_code;
            model.invoice_name = req.invoice_name;
            model.invoice_phone = req.invoice_phone;
            model.invoice_bank = req.invoice_bank;
            model.invoice_bank_code = req.invoice_bank_code;
            model.invoice_address = req.invoice_address;
            model.invoice_mobile = req.invoice_mobile;
            model.invoice_receipt_address = req.invoice_receipt_address;

            model.payable_amount = Utils.StrToDecimal(req.order_price,0) - Utils.StrToDecimal(req.freight,0);
            model.real_amount = Utils.StrToDecimal(req.order_price, 0) - Utils.StrToDecimal(req.freight, 0);
            model.express_status = 1;
            model.express_fee = Utils.StrToDecimal(req.freight, 0);
            model.payment_fee = 0;
            model.payment_status = 0; //标记未付款
            model.status = 1;

            //订单总金额=实付商品金额+运费+支付手续费+税金
            model.order_amount = Utils.StrToDecimal(req.order_price, 0);
            //购物积分,可为负数
            model.point = 0;
            //订单模式：1-协议价（默认）)；2-团购模式； 3-特惠模式; 4-阶梯价模式 
            model.mode = Utils.StrToInt(req.mode, 1);
            model.add_time = DateTime.Now;
            //商品详细列表
            BLL.article articleBLL = new BLL.article();
            List<Entitys.dt_order_goods> gls = new List<Entitys.dt_order_goods>();
            foreach (SubmitSku item in req.skuObj)
            {
                //检查库存数量
                if (new BLL.article().GetStockQuantity(2, Utils.ObjToInt(item.sku, 0), 0) < item.num)
                {
                    //库存不足
                    resp.success = false;
                    resp.desc = "out of stock";
                    var result_err = new HttpResponseMessage()
                    {
                        Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                    };
                    return result_err;
                }
                Entitys.article article = articleBLL.GetModel(2, Utils.ObjToInt(item.sku, 0));
                if (article != null)
                {
                    //添加进订单列表
                    gls.Add(new Entitys.dt_order_goods
                    {
                        channel_id = article.channel_id,
                        article_id = article.id,
                        goods_id = 0,
                        goods_no = Utils.ObjectToStr(article.fields["goods_no"]),
                        goods_title = Utils.ObjectToStr(article.title),
                        img_url = Utils.ObjectToStr(article.img_url),
                        spec_text = "",
                        goods_price = Utils.ObjToDecimal(article.fields["sell_price"]),
                        real_price = Utils.ObjToDecimal(article.fields["sell_price"]),
                        quantity = item.num,
                        point = 0
                    });
                }
            }
            model.order_goods = gls;
            int db_result = new BLL.orders().Add(model);
            if (db_result < 1)
            {
                //订单错误
                resp.success = false;
                resp.desc = "system error";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            SubmitResponse sr = new SubmitResponse();
            sr.mall_order_id = model.order_no;
            sr.orderPrice = Utils.ObjToDecimal(model.order_amount);
            sr.freight = Utils.ObjToDecimal(model.express_fee);
            sr.sku = req.skuObj;

            resp.success = true;
            resp.result = sr;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("confirm")]
        public HttpResponseMessage confirm()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            ConfirmRequest req = DTRequest.RequestFormParams<ConfirmRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.order_id))
            {
                resp.success = false;
                resp.desc = "order_id is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            BLL.orders bll = new BLL.orders();

            if (!bll.Exists(req.order_id))
            {
                resp.success = false;
                resp.desc = "order do not exist";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }
            Entitys.dt_orders model = bll.GetModel(req.order_id);
            //确认订单
            bll.UpdateField(x => new Entitys.dt_orders() { status = 3, confirm_time = DateTime.Now }, x => x.order_no == req.order_id);

            resp.success = true;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("cancel")]
        public HttpResponseMessage cancel()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            CancelRequest req = DTRequest.RequestFormParams<CancelRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.order_id))
            {
                resp.success = false;
                resp.desc = "order_id is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            BLL.orders bll = new BLL.orders();

            if (!bll.Exists(req.order_id))
            {
                resp.success = false;
                resp.desc = "order do not exist";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }
            bll.UpdateField(x => new Entitys.dt_orders() { status = 4 }, x => x.order_no == req.order_id);

            resp.success = true;


            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("select")]
        public HttpResponseMessage select()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            SelectRequest req = DTRequest.RequestFormParams<SelectRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.order_id))
            {
                resp.success = false;
                resp.desc = "order_id is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            BLL.orders bll = new BLL.orders();

            if (!bll.Exists(req.order_id))
            {
                resp.success = false;
                resp.desc = "order do not exist";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }
            Entitys.dt_orders model = bll.GetModel(req.order_id);

            SelectResponse sr = new SelectResponse();
            sr.order_id = model.order_no;

            if (model.express_status == 1|| model.express_status == 2)
                sr.state = 0;
            else if (model.express_status == 3)
                sr.state = 1;
            else if (model.express_status == 4)
                sr.state = -1;
            else if (model.express_status == 5)
                sr.state = 4;

            if (model.status == 1)
                sr.submit_state = 0;
            else if (model.status == 2 || model.status == 3)
                sr.submit_state = 1;

            ///deliver_state=2部分发货，不做此功能
            if (model.express_status == 1)
                sr.deliver_state = 0;
            else if (model.express_status == 2 || model.status == 3)
                sr.deliver_state = 1;

            sr.total_price = Utils.ObjToDecimal(model.order_amount);

            sr.skus = new List<SubmitSku>();
            foreach (Entitys.dt_order_goods item in model.order_goods)
            {
                SubmitSku sku = new SubmitSku();
                sku.sku = item.article_id.ToString();
                sku.num = item.quantity;
                sku.price = item.real_price;
                sr.skus.Add(sku);
            }

            sr.return_skus = new List<SubmitSku>();

            resp.success = true;
            resp.result = sr;

            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }


        [HttpPost]
        [Route("track")]
        public HttpResponseMessage track()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象

            SelectRequest req = DTRequest.RequestFormParams<SelectRequest>(request);
            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(req));
            BaseResponse resp = new BaseResponse();
            if (string.IsNullOrEmpty(req.order_id))
            {
                resp.success = false;
                resp.desc = "order_id is null";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }

            BLL.orders bll = new BLL.orders();

            if (!bll.Exists(req.order_id))
            {
                resp.success = false;
                resp.desc = "order do not exist";
                var result_err = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
                };
                return result_err;
            }
            Entitys.dt_orders model = bll.GetModel(req.order_id);

            TrackResponse tr = new TrackResponse();
            tr.track = new List<Track>();
            Track t = new Track();
            t.content = "无";
            t.operate_time = Utils.ObjectToDateTime(model.express_time, DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss");
            t.@operator = "供应商";
            tr.track.Add(t);

            tr.waybill = new List<Waybill>();
            Waybill w = new Waybill();
            w.order_id = model.order_no;
            w.logistic_type = model.express_id == 1 ? 1 : Utils.ObjToInt(model.express_id);
            w.logistic_name = new BLL.express().GetTitle(Utils.ObjToInt(model.express_id));
            w.logistic_no = model.express_no.IsNullOrEmpty() ? " " : model.express_no;
            w.shipment_id = "FH" + model.order_no;
            w.shipment_items = new List<SubmitSku>();
            foreach (Entitys.dt_order_goods item in model.order_goods)
            {
                SubmitSku sku = new SubmitSku();
                sku.sku = item.article_id.ToString();
                sku.num = item.quantity;
                sku.price = item.real_price;
                w.shipment_items.Add(sku);
            }
            tr.waybill.Add(w);


            resp.success = true;
            resp.result = tr;

            LoggerHelper.Debug(JsonHelper2.ObjectToJSON(resp));
            var result = new HttpResponseMessage()
            {
                Content = new StringContent(JsonHelper2.ObjectToJSON(resp), Encoding.UTF8, "application/json")
            };
            return result;
        }

    }
}